package com.mx.zb.mng.utils;

import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.mx.zb.mng.bo.AgentLog;
import com.mx.zb.mng.bo.Operator;
import com.mx.zb.mng.dao.AgentLogMapper;
import com.mx.zb.mng.dao.OperatorMapper;
import com.mx.zb.mng.utils.context.CommonRequestWrapper;
import com.mx.zb.mng.utils.context.JsonConfig;


@Component
public class LogManage {
	
	@Autowired
	AgentLogMapper  agentLogMapper;
	
	@Autowired
	OperatorMapper operatorMapper;
	public void saveAgentLog(HttpServletRequest request) {
		String currenPath = request.getRequestURI();
    	String currenMethod=request.getMethod();
    	String name=JsonConfig.get(currenPath, currenMethod);
    	if(!StringUtils.hasText(name)) 
    	     return;
    	String param=getParam(request);
    	if(!StringUtils.hasText(param)) {
    		param="";
    		StringBuilder sb=new   StringBuilder();
    		Enumeration enu=request.getParameterNames();  
    		while(enu.hasMoreElements()){  
    			String  paraName=(String)enu.nextElement();  
    			//param+=paraName+": "+request.getParameter(paraName)+",";
    			//sb.append(paraName+": "+request.getParameter(paraName)+",");
    			sb.append(paraName);
    			sb.append(": ");
    			sb.append(request.getParameter(paraName));
    			sb.append(",");
    		}
    		param=sb.toString();
    	}

		System.out.println(param);
    	String ip=Ip.getRemoteIp(request);
    	AgentLog log=new AgentLog();
        HttpSession session = request.getSession();
        String operatorId=session.getAttribute("operatorId").toString();
        String agentId = (String)session.getAttribute("agentId");
        Operator operator=operatorMapper.selectByPrimaryKey(operatorId);
        log.setIp(ip);
    	log.setAgentId(agentId);
    	log.setCreateDate(new Date());
    	log.setId(UnionCode.getShortUuid());
        log.setName(name);
        if(StringUtils.hasText(param)&&param.length()>2501) {
        	param=param.substring(0,2500);
        }
        log.setCreateOper(operatorId);
        log.setCreateName(operator.getLoginName());
        log.setParam(param);
        agentLogMapper.insertSelective(log);
	}
	
	public String getParam(HttpServletRequest request) {
		CommonRequestWrapper req = (CommonRequestWrapper) request;
		return req.getBody();
		/*String str,wholeStr = "";
		 try {
					BufferedReader br;
						br = request.getReader();
					
					while((str = br.readLine()) != null){
					wholeStr += str;
					}

					System.out.println(wholeStr);
	        }catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
	}
			return wholeStr;*/
	  
}
	
}
